package com.glsc.ngateway.flowable.controller;

import com.glsc.ngateway.common.api.flowable.dto.ParamEmailDto;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableAppendDto;
import com.glsc.ngateway.common.api.flowable.resp.FlowableResponse;
import com.glsc.ngateway.common.api.flowable.resp.ResponseUploadDto;
import com.glsc.ngateway.flowable.constant.FlowableConstant;
import com.glsc.ngateway.flowable.service.FlowableAppendService;
import com.glsc.ngateway.flowable.service.MailService;
import com.glsc.ngateway.flowable.util.DateUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/common")
@Api(value = "flowable流程辅助类", tags = {"flowable流程辅助类"})
public class CommonController {

    private static Logger logger = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    FlowableAppendService appendixService;

    @Autowired
    MailService mailService;

    /**
     * @return
     * @throws IOException
     * @description 上传附件
     */
    @RequestMapping(method = RequestMethod.POST, value = "/sendMail")
    public void send(@RequestBody ParamEmailDto emailReport) throws Exception {
        mailService.sendEmail(emailReport);
    }


    /**
     * @param file
     * @return
     * @throws IOException
     * @description 上传附件
     */
    @RequestMapping(method = RequestMethod.POST, value = "/uploadDoc", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public FlowableResponse<ResponseUploadDto> uploadDoc(@RequestPart(value = "file") MultipartFile[] file) throws IOException {
        logger.info("接收文件，并进行上传，时间:" + DateUtil.getCurrentDate(DateUtil.formatSecond));
        List<Map<String, String>> fileList = new ArrayList<Map<String, String>>();
        for (MultipartFile f : file) {
            Map appendixMap = new HashMap();
            appendixMap.put("annexName", f.getOriginalFilename());
            String appendixId = appendixService.updateAppendix(f.getOriginalFilename(), FlowableConstant.UP_FILE, f);
            logger.info("接收文件，并进行上传，文件名称:" + f.getOriginalFilename() + ",时间:" + DateUtil.getCurrentDate(DateUtil.formatSecond));
            appendixMap.put("annexId", appendixId);
            fileList.add(appendixMap);
        }
        logger.info("完成文件上传，时间:" + DateUtil.getCurrentDate(DateUtil.formatSecond));
        return FlowableResponse.success(new ResponseUploadDto(fileList));
    }


    /**
     * @description 下载附件
     */
    @RequestMapping(method = RequestMethod.POST, value = "oaDownloadAppendix/{appendixId}")
    public ResponseEntity<byte[]> oaDownloadAppendix(@PathVariable("appendixId") String appendixId, HttpServletRequest request) throws IOException {

        String targetName = appendixService.getAppendixPathById(appendixId);
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }

    /**
     * @description 下载附件
     */
    @RequestMapping(method = RequestMethod.GET, value = "/downloadDemandAppendix")
    public ResponseEntity<byte[]> downloadDemandAppendix(@RequestParam("appendixId") String appendixId) throws IOException {

        String targetName = appendixService.getAppendixPathById(appendixId);
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/getAppendixInfos")
    public ResponseEntity<List<FlowableAppendDto>> getAppendixInfos(@RequestBody List<String> appendixIds) throws IOException {

        List<FlowableAppendDto> target = appendixService.findByAppendixIdIn(appendixIds);
        return new ResponseEntity<List<FlowableAppendDto>>(target, HttpStatus.OK);
    }
}
